<?php

namespace addons\wwh\controller;

use think\Db;
use fast\Tree;

class Base extends \think\addons\Controller
{
    /**
     * 初始化控制器
     */
    public function _initialize()
    {
        //测试远程部署3
        parent::_initialize();

        // 初始化语言设置
        $this->initLanguage();

        // 加载站点配置
        $this->loadSiteConfig();

        // 初始化导航数据
        $this->initNavigation();
    }

    /**
     * 初始化语言设置
     */
    protected function initLanguage()
    {
        $config = get_addon_config('wwh');
        $switch_lang = $config['switch_lang'];

        // 检测URL参数
        $urlLang = $this->request->get('lang', '', 'strtolower');
        if (in_array($urlLang, ['zh-cn', 'en'])) {
            $this->lang = ($urlLang == 'zh-cn') ? 1 : 2;
            cookie('lang', $this->lang, 3600 * 24 * 30);
        } else {
            // 检测cookie
            $this->lang = (int)cookie('lang');
            // 默认配置
            if (empty($this->lang) && !empty($config['set_lang'])) {
                $this->lang = $config['set_lang'];
                cookie('lang', $this->lang, 3600 * 24 * 30);
            }
        }

        $this->assign([
            'switch_lang' => $switch_lang,
            'lang' => $this->lang
        ]);
    }

    /**
     * 加载站点配置
     */
    protected function loadSiteConfig()
    {
        $site = Db::name('wwh_config')
            ->where('lang', $this->lang)
            ->find();

        if (empty($site)) {
            $this->error('站点配置数据为空');
        }

        $this->assign('site', $site);

        // 设置模板路径
        $this->view->engine->config(
            'view_path',
            $this->view->engine->config('view_path') . $site['template'] . DS
        );
    }

    /**
     * 初始化导航数据
     */
    protected function initNavigation()
    {
        // 获取所有正常状态的栏目
        $columns = Db::name('wwh_column')
            ->where('status', 'normal')
            ->where('lang', $this->lang)
            ->order('weigh desc')
            ->select();

        // 主导航
        $navList = array_filter($columns, function($item) {
            return $item['isnav'] == '1';
        });

        $navTree = Tree::instance()
            ->init(collection($navList)->toArray(), 'parent_id')
            ->getTreeArray(0);
        $this->assign('nav', $navTree);

        // 资料下载导航
        $fullTree = Tree::instance()
            ->init(collection($columns)->toArray(), 'parent_id')
            ->getTreeArray(0);
        $this->assign('nav2', $fullTree);

        // 导航ID
        $navMap = array_column($columns, null, 'id');
        $this->assign('navId', $navMap);
    }
}
